/**
 * Project Name:scapp-web
 * File Name:CustomerController.java
 * Package Name:com.sc.controller
 * Date:2018年7月2日上午11:55:49
 * Copyright (c) 2018, bluemobi All Rights Reserved.
 */

package com.sc.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sc.app.restful.DataResult;
import com.sc.app.restful.ListResult;
import com.sc.pojo.Appointment;
import com.sc.pojo.Customer;
import com.sc.pojo.CustomerGrand;
import com.sc.service.CustomerService;

/**
 * Description: <br/>
 * Date: 2018年7月2日 上午11:55:49 <br/>
 * 
 * @author tianyongxu
 * @version
 * @see
 */
@Controller
// @RequestMapping(value = "/CustomerController")
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    // 田永旭开始---------------->

    /**
     * 查询所有的员工
     */
    // @ResponseBody 返回值类型 list<Customer>-->String
    @RequestMapping(value = "selectAllCustomers")
    public String selectAllCustomers(Model model) {
        List<Customer> listCustomers = customerService.selectCustomers();// 获取对象
        Float singleProbability = null;
        String percentage = "";
        CustomerGrand customerGrand = null;
        List<CustomerGrand> listCustomerGrands = new ArrayList<CustomerGrand>();
        // 通过有的客户获取所有客户对应的概率
        for (int i = 0; i < listCustomers.size(); i++) {
            customerGrand = new CustomerGrand();// 每次都存新对象
            singleProbability = customerService.selectBuyHouseProbability(listCustomers.get(i)) * 100f;// 把整数变为百分数；
            percentage = Math.floor(singleProbability) + "%";
            customerGrand.setCustomer(listCustomers.get(i));
            customerGrand.setProbability(percentage);

            listCustomerGrands.add(customerGrand);
        }
        model.addAttribute("listCustomerGrands", listCustomerGrands);

        return "sc-customermanagement";
    }

    /**
     * 通过id查询某个员工
     */
    // @ResponseBody @PathVariable("cid")
    @RequestMapping(value = "selectCustomer")
    public String selectCustomerById(Integer cid, Model model) {
        System.out.println("从路径上获取的id" + cid);
        Customer customer = customerService.selectCustomersByCid(cid);
        model.addAttribute("customer", customer);
        return "sc-customerinfo";
    }

    /**
     * 通过id查询某个员工
     */
    // @ResponseBody @PathVariable("cid")
    @RequestMapping(value = "selectCustomerForChangeok")
    public String selectCustomerByIdForChnage(Integer cid, Model model) {
        System.out.println("从路径上获取的id--->" + cid);
        Customer customer = customerService.selectCustomersByCid(cid);
        model.addAttribute("customer", customer);
        return "sc-customerinfo";
    }

    /**
     * 通过id查询某个员工为了修改客户信息
     */
    // @ResponseBody @PathVariable("cid")
    @RequestMapping(value = "selectCustomerForChange")
    public String selectCustomerByIdForChange(Integer cid, Model model) {
        System.out.println("从路径上获取的id" + cid);
        Customer customer = customerService.selectCustomersByCid(cid);

        model.addAttribute("customer", customer);
        return "sc-changecustormerinfo";
    }

    /**
     * 根据电话查询用户是否存在于用户表中
     */
    @ResponseBody
    @RequestMapping(value = "selectappointmentbyPhone")
    public int selectappointmentbyPhone(String cphone) {
        System.out.println("电话查询" + cphone);
        List<Customer> list = customerService.selectbyPhone(cphone);
        System.out.println(list.size());
        return list.size();

    }

    // 没用到
    /**
     * 查询所有计算好的概率值 普通的
     */
    @ResponseBody
    @RequestMapping(value = "selectAllProbability")
    public List<Float> selectAllProbability() {
        List<Customer> listCustomers = customerService.selectCustomers();
        List<Float> listFloats = new ArrayList<Float>();
        // 通过有的客户获取所有客户对应的概率
        for (int i = 0; i < listCustomers.size(); i++) {
            // 获取单个概率
            System.out.println("这个客户是？？" + listCustomers.get(i));
            listFloats.add(customerService.selectBuyHouseProbability(listCustomers.get(i)));
        }
        return listFloats;

    }

    /**
     * 通过id删除某个员工,返回删除基本信息
     */
    // @ResponseBody @PathVariable("cid")
    @RequestMapping(value = "deleteCustomerById")
    public String deleteCustomerById(Integer cid) {
        Customer customerDelete = customerService.selectCustomersByCid(cid);// 放在删除前，不然空指针
        int deleteByPrimaryKey = customerService.deleteByPrimaryKey(cid);
        if (deleteByPrimaryKey > 0) {

            return "sc-customermanagement";
        }
        return "sc-customerinfo";
    }

    /**
     * 修改某个客户的信息
     */
    // 为什么不能将值返回去

    @RequestMapping(value = "updateCustomer")
    public @ResponseBody Customer updateCustomer(Customer customerForChange, Model model) {// 从页面显示出来
        System.out.println("进入了修改方法");
        customerService.updateByPrimaryKeySelective(customerForChange);
        System.out.println(customerForChange.getCname() + customerForChange.getCid());
        Customer customer = customerService.selectCustomersByCid(customerForChange.getCid());
        System.out.println(customer.getChousetype());
        return customer;
    }

    /**
     * 
     * 按照客户的等级排名查询
     */
    // @ResponseBody
    @RequestMapping(value = "selectCustomerByGrand")
    public String selectCustomerByGrand(Model model) {
        /**
         * List<Customer> listCustomers = customerService.selectCustomers();
         * Map<Object, String> custMap = new HashMap<Object, String>(); Float
         * singleProbability = null; String percentage = ""; //
         * 通过有的客户获取所有客户对应的概率 for (int i = 0; i < listCustomers.size(); i++) {
         * singleProbability =
         * customerService.selectBuyHouseProbability(listCustomers.get(i))*100f;//把整数变为百分数；
         * percentage = Math.floor(singleProbability)+"%";
         * custMap.put(listCustomers.get(i), percentage); }
         * //有个极大的问题，map的键值要唯一，现在有的概率值很多都一样，所以不能显示完全 //1.想要把员工作为键，概率值为值
         * model.addAttribute("custMap", custMap);
         */
        List<Customer> listCustomers = customerService.selectCustomersByGrand();// 按照等级查好的数据
        Float singleProbability = null;// 定义单个概率
        String percentage = "";// 概率转为%
        CustomerGrand customerGrand = null;
        List<CustomerGrand> listCustomerGrands = new ArrayList<CustomerGrand>();
        for (int i = 0; i < listCustomers.size(); i++) {
            customerGrand = new CustomerGrand();
            singleProbability = customerService.selectBuyHouseProbability(listCustomers.get(i)) * 100f;// 把整数变为百分数；
            percentage = Math.floor(singleProbability) + "%";
            customerGrand.setCustomer(listCustomers.get(i));
            customerGrand.setProbability(percentage);
            listCustomerGrands.add(customerGrand);
        }
        model.addAttribute("listCustomerGrands", listCustomerGrands);
        return "sc-customermanagement";
    }

    /**
     * 根据客户等级排名 的概率 配套等级查询用的
     */
    @ResponseBody
    @RequestMapping(value = "selectProbabilityByGrand")
    public List<Float> selectProbabilityByGrand() {
        List<Customer> customersListGrand = customerService.selectCustomersByGrand();
        List<Float> listFloats = new ArrayList<Float>();
        for (int i = 0; i < customersListGrand.size(); i++) {
            listFloats.add(customerService.selectBuyHouseProbability(customersListGrand.get(i)));
        }
        return listFloats;
    }

    /**
     * 与下面的方法合起来用 将买房概率进行从高到高低排出来
     */
    @ResponseBody
    @RequestMapping(value = "selectAllProbabilityDesc")
    public List<Float> selectAllProbabilityDesc() {
        List<Customer> listCustomers = customerService.selectCustomers();
        List<Float> listFloats = new ArrayList<Float>();
        // 通过有的客户获取所有客户对应的概率
        for (int i = 0; i < listCustomers.size(); i++) {
            // 获取单个概率
            System.out.println("这个客户是？？" + listCustomers.get(i));
            listFloats.add(customerService.selectBuyHouseProbability(listCustomers.get(i)));
        }
        Collections.sort(listFloats);
        return listFloats;

    }

    /**
     * 根据概率的排名显示对应的员工信息
     */
    // @ResponseBody List<Customer>
    @RequestMapping(value = "selectCustomersSameProbability")
    public String selectCustomersSameProbability(Model model) {
        Map<Integer, Float> customerMap = new TreeMap<Integer, Float>();

        List<Customer> listCustomers = customerService.selectCustomers();// 表里面的客户列表

        List<Customer> listCustomersProbability = new ArrayList<Customer>();// 用来装排好数据的集合
        // List<Float> listFloats = new ArrayList<Float>();
        // 通过有的客户获取所有客户对应的概率
        for (int i = 0; i < listCustomers.size(); i++) {
            // 获取单个概率
            // System.out.println("这个客户是？？"+listCustomers.get(i));
            // key:代表cid value:代表这个id代表的客户的概率值
            customerMap.put(listCustomers.get(i).getCid(),
                    customerService.selectBuyHouseProbability(listCustomers.get(i)));
        }
        List<Map.Entry<Integer, Float>> listProbability = new ArrayList<Map.Entry<Integer, Float>>(
                customerMap.entrySet());
        Collections.sort(listProbability, new Comparator<Map.Entry<Integer, Float>>() {

            @Override
            public int compare(Map.Entry<Integer, Float> o1, Map.Entry<Integer, Float> o2) {
                // Auto-generated method stub
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        // 为了返回客户信息集合
        Float singleProbability = null;
        String percentage = "";
        CustomerGrand customerGrand = null;
        List<CustomerGrand> listCustomerGrands = new ArrayList<CustomerGrand>();
        for (Map.Entry<Integer, Float> entry : listProbability) {
            // System.out.println(entry.getKey()+":"+entry.getValue());
            customerGrand = new CustomerGrand();
            singleProbability = customerService
                    .selectBuyHouseProbability(customerService.selectCustomersByCid(entry.getKey())) * 100f;// 把整数变为百分数；
            percentage = Math.floor(singleProbability) + "%";
            customerGrand.setCustomer(customerService.selectCustomersByCid(entry.getKey()));
            customerGrand.setProbability(percentage);
            listCustomerGrands.add(customerGrand);
            listCustomersProbability.add(customerService.selectCustomersByCid(entry.getKey()));
        }
        model.addAttribute("listCustomerGrands", listCustomerGrands);

        return "sc-customermanagement";
    }

    /**
     * 模糊查询的方法
     */
    @ResponseBody
    @RequestMapping(value = "selectCustomersLike/{cname}")
    public List<Customer> selectCustomersLike(@PathVariable("cname") String cname) {
        return customerService.selectCustomersLike(cname);
    }

    // 田永旭结束----------------->

    /**
     * Q -start
     */

    static void setContAndHeader(HttpServletResponse response) {
        /* if(aus.verification(username, password)>0){ */
        response.setContentType("text/html;charset=utf-8");
        // 设置响应头允许ajax跨域访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 星号表示所有的异域请求都可以接受，
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");
    }

    @RequestMapping("selectLikeCustomerInfo")
    @ResponseBody
    public ListResult<Customer> selectLikeCustomerInfo(HttpServletResponse response, String likeInfo, Integer eid) {
        setContAndHeader(response);
        System.out.println("获取的值：" + likeInfo + "员工id：" + eid);
        List<Customer> cus = null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("eid", eid);
        if (likeInfo.matches("[0-9]+")) {
            System.out.println("您输入了手机号");
            map.put("cphone", "'%" + likeInfo + "%'");
            cus = customerService.selectDynamicByInfo(map);
        } else if (likeInfo.trim().length() > 0) {
            System.out.println("您输入了名字");
            map.put("name", "'%" + likeInfo + "%'");
            cus = customerService.selectDynamicByInfo(map);
        }
        System.out.println("结果：" + cus);
        return new ListResult<Customer>(cus);

    }

    @ResponseBody
    @RequestMapping(value = "listCall")
    public ListResult<Customer> listCall(HttpServletResponse response, Integer eid) {
        setContAndHeader(response);
        System.out.println("进来了");
        setContAndHeader(response);
        System.out.println("获取的eid：" + eid);

        List<Customer> list = customerService.selectByEmIdCuInfo(eid);
        System.out.println(list);
        return new ListResult<Customer>(list);
    }

    @ResponseBody
    @RequestMapping(value = "insertRport")
    public DataResult<Integer> insertRport(HttpServletResponse response, Integer eid, String cphone, String cname,
            String cgender) {
        setContAndHeader(response);
        System.out.println("进来了");
        setContAndHeader(response);
        System.out.println("获取的eid：" + eid);
        Date day = new Date();
        int out = 0;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("e_id", eid);
        map.put("c_phone", cphone);
        map.put("c_gender", cgender);
        map.put("c_name", cname);
        map.put("c_date", df.format(day));
        map.put("c_out", out);
        int flag = customerService.insertReport(map);
        System.out.println("flag：" + flag + "out：" + map.get("c_out"));
        out = Integer.parseInt(map.get("c_out").toString());
        return new DataResult<Integer>(out);
    }

    @ResponseBody
    @RequestMapping(value = "selectOrder")
    public ListResult<Customer> selectOrder(HttpServletResponse response, Integer eid) {
        setContAndHeader(response);
        List<Customer> list = customerService.selectCustomerOrderByEid(eid);

        System.out.println(list);

        // 查询处理信息
        return new ListResult<Customer>(list);

    }

    @ResponseBody
    @RequestMapping(value = "selectCuHoseTypeInfoByEid")
    public ListResult<Customer> selectCuHoseTypeInfoByEid(HttpServletResponse response, Integer eid) {
        setContAndHeader(response);
        List<Customer> list = customerService.selectCustomerByHouseType(eid);
        for (int i = 0; i < list.size(); i++) {

            Customer customer = list.get(i);
            Appointment ap = new Appointment();
            ap.setAimage(customerService.selectImageByCid(customer.getCid()));
            customer.setAppointment(ap);

        }
        System.out.println(list);
        // 查询处理信息
        return new ListResult<Customer>(list);

    }

    @ResponseBody
    @RequestMapping(value = "selectCustomerInfoByCid")
    public DataResult<Customer> selectCustomerInfoByCid(HttpServletResponse response, Integer cid) {
        setContAndHeader(response);
        Customer cu = customerService.selectByCid(cid);
        System.out.println(cid);

        return new DataResult<Customer>(cu);

    }

    @ResponseBody
    @RequestMapping(value = "updateEntering")
    public DataResult<Integer> updateEntering(HttpServletResponse response, Customer customer) {
        setContAndHeader(response);
        System.out.println(customer);
        int flag = customerService.updateByCustomer(customer);

        return new DataResult<Integer>(flag);
    }

    @ResponseBody
    @RequestMapping(value = "echarts")
    public DataResult<Map<String, Object>> echarts(HttpServletResponse response, Integer cid) {
        setContAndHeader(response);
        System.out.println(cid);
        Map<String, Object> map = customerService.selectCuEachrtsBycid(cid);
        System.out.println(map);
        return new DataResult<Map<String, Object>>(map);
    }

    /**
     * Q -end
     */

}
